package main

import (
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

/**
  地址：https://leetcode-cn.com/problems/add-two-numbers/
*/
func addTwoNumbers(l1, l2 *ListNode) (head *ListNode) {
	var tail *ListNode
	carry := 0
	for l1 != nil || l2 != nil {
		val1, val2 := 0, 0
		if l1 != nil {
			val1 = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			val2 = l2.Val
			l2 = l2.Next
		}
		sum := val1 + val2 + carry
		sum, carry = sum%10, sum/10
		if head == nil {
			head = &ListNode{Val: sum % 10}
			tail = head
		} else {
			tail.Next = &ListNode{Val: sum % 10}
			tail = tail.Next
		}
	}
	if carry > 0 {
		tail.Next = &ListNode{Val: carry}
	}
	return head
}

func printList(node *ListNode) {
	collect := make([]int, 0)
	for node != nil {
		collect = append(collect, node.Val)
		node = node.Next
	}
	fmt.Println(collect)
}

func main() {
	printList(addTwoNumbers(
		&ListNode{2, &ListNode{4, &ListNode{Val: 3}}},
		&ListNode{5, &ListNode{6, &ListNode{Val: 4}}}))
	printList(addTwoNumbers(
		&ListNode{},
		&ListNode{}))
	printList(addTwoNumbers(
		&ListNode{9, &ListNode{9, &ListNode{9, &ListNode{9, &ListNode{9, &ListNode{9, &ListNode{Val: 9}}}}}}},
		&ListNode{9, &ListNode{9, &ListNode{9, &ListNode{Val: 9}}}}))
}
